package cn.yuanqiao.web.controller.cqbc;
/**
 * @author 赵常飞
 * @date 2024/6/14 14:53
 */

import cn.yuanqiao.common.core.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.cqbc.common.mapper.MapperToolsMapper;
import cn.yuanqiao.cqbc.dataManage.domain.DataManage;
import cn.yuanqiao.cqbc.dataManage.service.IDataManageService;
import cn.yuanqiao.cqbc.dataManageTreePath.domain.DataManageTreePath;
import cn.yuanqiao.cqbc.dataManageTreePath.service.impl.IDataManageTreePathServiceImpl;
import cn.yuanqiao.cqbc.util.EEPUtil;
import cn.yuanqiao.cqbc.util.MD5Util;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.HtmlUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 *@Author: 赵常飞
 *@Date: 2024/6/14 14:53
 *@Description:
 *@Note:
 */
@RestController
@RequestMapping("/cqbc/receiveDetection")
public class ReceiveDetectionController extends BaseController {

    @Autowired
    private IDataManageService dataManageService;
    @Autowired
    private IDataManageTreePathServiceImpl dataManageTreePathService;
    @Autowired
    private MapperToolsMapper DbTool;
    @Autowired
    private EEPUtil eepUtil;

    @Log(title = "目录解析",businessType= BusinessType.OTHER)
    @PostMapping("/dirParsing")
    public AjaxResult dirParsing(@RequestBody DataManage dataManage) {
        try {
            String categoryType = dataManage.getZlfs();
            dataManage.setName( HtmlUtils.htmlUnescape(dataManage.getName().replaceAll(" ","")));
            String filePath = dataManage.getPath()+File.separator+dataManage.getName()+"."+dataManage.getFormat();

            String tenantCode=SecurityUtils.getLoginUser().getSysUser().getTenantCode();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("data_id",dataManage.getId());
            resultMap.put("categoryId",dataManage.getCategory());
            resultMap.put("tenantCode",tenantCode);
            resultMap.put("path",dataManage.getPath());
            resultMap.put("name",dataManage.getName()+"."+dataManage.getFormat());
            //插入MD5值开始
            File file = new File(filePath);
            String md5Str = "";
            if(file.exists()){
                md5Str = MD5Util.md5Encode(file, "MD5");
            }
            DataManage dataManage1 = new DataManage();
            dataManage1.setId(dataManage.getId());
            dataManage1.setMd5Str(md5Str);
            dataManageService.update(dataManage1);
            //插入MD5值结束
            DataManageTreePath dataManageTreePath1=new DataManageTreePath();
            dataManageTreePath1.setCategoryId(dataManage.getCategory());
            DataManageTreePath dataManageTreePath = dataManageTreePathService.selectpath(dataManageTreePath1);
            if(null==dataManageTreePath.getId()){
                return AjaxResult.error("此包对应门类未设置存储位置!");
            }
            resultMap.put("pathId",dataManageTreePath.getId());
            JSONObject resultDaMap = eepUtil.receiveEEPPackeg(resultMap, HtmlUtils.htmlUnescape(filePath.replaceAll(" ","")),dataManage);
            //Map maps = (Map) JSON.parse(str.substring(0,str.indexOf("}")+1));
            //yqDataManageParam.setCategory(yqDataManageParam.getCategory());
            dataManage.setSize(null);
            dataManage.setResolved("1");

            String categoryPath = dataManageTreePath.getPath();
            String pathId=String.valueOf(dataManageTreePath.getId());

            String newFilePath = categoryPath;

            moveFileToPathNoTimeSpac(filePath,newFilePath);

            dataManage.setPath(newFilePath);

            dataManageService.update(dataManage);

            if ("f".equals(categoryType)){
                int i = DbTool.executeUpdate("UPDATE "+tenantCode+"_CQBC_HDDA  SET EEP_PATH = '"+newFilePath+"',EEP_PATH_ID='"+pathId+"' WHERE DATA_ID = "+dataManage.getId());
            }else if("v".equals(categoryType)){
                int i = DbTool.executeUpdate("UPDATE "+tenantCode+"_CQBC_FOLDER SET EEP_PATH = '"+newFilePath+"',EEP_PATH_ID='"+pathId+"' WHERE DATA_ID = "+dataManage.getId());
                int i1 = DbTool.executeUpdate("UPDATE "+tenantCode+"_CQBC_HDDA SET EEP_PATH = '"+newFilePath+"',EEP_PATH_ID='"+pathId+"' WHERE DATA_ID = "+dataManage.getId());
            }else if("x".equals(categoryType)){
                int i = DbTool.executeUpdate("UPDATE "+tenantCode+"_CQBC_FOLDER SET EEP_PATH = '"+newFilePath+"',EEP_PATH_ID='"+pathId+"' WHERE DATA_ID = "+dataManage.getId());
                int i1 = DbTool.executeUpdate("UPDATE "+tenantCode+"_CQBC_HDDA SET EEP_PATH = '"+newFilePath+"',EEP_PATH_ID='"+pathId+"' WHERE DATA_ID = "+dataManage.getId());
                int i2 = DbTool.executeUpdate("UPDATE "+tenantCode+"_CQBC_ITEM SET EEP_PATH = '"+newFilePath+"',EEP_PATH_ID='"+pathId+"' WHERE DATA_ID = "+dataManage.getId());
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    private boolean moveFileToPathNoTimeSpac(String newFile,String newPath){
        boolean flag = false;
        File startFile=new File(newFile);
        File endDirection=new File(newPath);
        if(!endDirection.exists()) {
            endDirection.mkdirs();
        }
        File endFile=new File(endDirection+ File.separator+ startFile.getName());
        try {
            if (startFile.renameTo(endFile)) {
                System.out.println("文件移动成功！目标路径：{"+endFile.getAbsolutePath()+"}");
                flag = true;
            } else {
                System.out.println("文件移动失败！起始路径：{"+startFile.getAbsolutePath()+"}");
            }
        }catch(Exception e) {
            System.out.println("文件移动出现异常！起始路径：{"+startFile.getAbsolutePath()+"}");
            e.printStackTrace();
        }
        return flag;
    }

    @Log(title = "四性检测",businessType= BusinessType.OTHER)
    @PostMapping("/fourCheck")
    public AjaxResult fourCheck(@RequestBody JSONObject json) {
        return AjaxResult.success(dataManageService.fourCheck(json));
    }


}
